package com.zzjson.provider;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2020 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.provider</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2020年02月23日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
@Component
@Getter
public class MyRpcServer implements ApplicationContextAware, InitializingBean {
	private int port;
	private Map<String, Object> handlerMap = new HashMap<>();
	ExecutorService executorService = Executors.newCachedThreadPool();

	public MyRpcServer(int port) {
		this.port = port;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		ServerSocket serverSocket = new ServerSocket(port);
		while (true) {
			Socket socket = serverSocket.accept();
			executorService.execute(new ProcessorHandler(socket, handlerMap));

		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RpcService.class);
		if (!serviceBeanMap.isEmpty()) {
			//获取每一个被注解的bean
			for (Object serviceBean : serviceBeanMap.values()) {
				//获取注解
				RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
				String serviceName = rpcService.value().getName();
				//获取版本号
				String version = rpcService.version();
				if (!StringUtils.isEmpty(version)) {
					serviceName += "-" + version;
				}
				handlerMap.put(serviceName, serviceBean);
			}
		}
	}
}
